package com.socket.nio.nio.sticky.linebased;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.CharsetUtil;

/**
 * 基于行分隔符的解码器 客户端
 *
 * @author Hexudong
 * @date 2025/5/5
 */
public class LineBasedClient {

  private final String host;

  private final int port;

  public LineBasedClient(String host, int port) {
    this.host = host;
    this.port = port;
  }

  public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();

    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
              // 添加固定长度解码器
              ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
              // 将ByteBuf转换为String
              ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
              ch.pipeline().addLast(new LineBasedClientHandler());
            }
          });
      ChannelFuture channelFuture = b.connect(this.host, this.port).sync();
      System.out.println("LineBasedClient started on port: " + this.port);

      Channel channel = channelFuture.channel();
      sendMessage(channel, "Hello Netty");
      sendMessage(channel, "LineBased Protocol");
      sendMessage(channel, "Length");
      channel.closeFuture().sync();
    } finally {
      group.shutdownGracefully();
    }
  }

  private void sendMessage(Channel channel, String msg) {
    String formattedMsg = msg + "\n";
    channel.writeAndFlush(Unpooled.copiedBuffer(formattedMsg, CharsetUtil.UTF_8));
  }

  public static void main(String[] args) throws Exception {
    new LineBasedClient("localhost", 8082).run();
  }
}
